//
//  MenuViewController.m
//  ProjectB
//
//  Created by lanou on 16/5/7.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "MenuViewController.h"
#import "LifeViewController.h"
#import "DeadTimeViewController.h"
#import "WishViewController.h"
#import <SVProgressHUD.h>
#import <MessageUI/MessageUI.h>
#import "UserTableViewController.h"

@interface MenuViewController ()<UITableViewDelegate, UITableViewDataSource, MFMailComposeViewControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UINavigationController *lifeNC;
@property (nonatomic, strong) UINavigationController *deadNC;
@property (nonatomic, strong) UIViewController *mainVC;
@property (nonatomic, strong) UITapGestureRecognizer *tap;
@property (nonatomic, assign) BOOL isOpen;
@property (nonatomic, strong) UILabel *usernameLabel;

@end

@implementation MenuViewController

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] initWithObjects:@"设置出生日期", @"关闭死之钟", /*@"我的心愿单",*/ @"反馈意见", @"去App Store评价我们", nil];
    }
    return _dataSource;
}

//- (void)viewDidAppear:(BOOL)animated {
//    [super viewDidAppear:animated];
//    
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        [self.deadNC.view removeFromSuperview];
//    });
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _isOpen = NO;
    [SVProgressHUD setMinimumDismissTimeInterval:0];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    
    _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50 * self.dataSource.count + 100) style:UITableViewStylePlain];
    _tableView.center = self.view.center;
    _tableView.rowHeight = 50;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    [self.view addSubview:_tableView];
    
    self.tableView.transform = CGAffineTransformMakeScale(2, 2);
    
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    LifeViewController *lifeVC = [[LifeViewController alloc] init];
    DeadTimeViewController *deadVC = [[DeadTimeViewController alloc] init];
    
    __weak MenuViewController *vc = self;
    lifeVC.changeUserBlock = ^{
        vc.usernameLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"];
    };
    lifeVC.deadBlock = ^{
        [vc.view addSubview:vc.deadNC.view];
        [UIView transitionFromView:vc.lifeNC.view toView:vc.deadNC.view duration:0.5 options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished) {
            vc.mainVC = vc.deadNC.viewControllers.firstObject;
        }];
        NSArray *array = [[NSArray alloc] initWithObjects:@"设置寿命预测", /*@"我的心愿单",*/ @"反馈意见", @"去App Store评价我们", nil];
        [vc.dataSource removeAllObjects];
        [vc.dataSource addObjectsFromArray:array];
        vc.tableView.height = 50 * vc.dataSource.count * 2 + 200;
        [vc.tableView reloadData];
    };
    deadVC.lifeBlock = ^{
        [vc.view addSubview:vc.lifeNC.view];
        [UIView transitionFromView:vc.deadNC.view toView:vc.lifeNC.view duration:0.5 options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished) {
            vc.mainVC = vc.lifeNC.viewControllers.firstObject;
        }];
        NSArray *array = [[NSArray alloc] initWithObjects:@"设置出生日期", @"关闭死之钟", /*@"我的心愿单",*/ @"反馈意见", @"去App Store评价我们", nil];
        [vc.dataSource removeAllObjects];
        [vc.dataSource addObjectsFromArray:array];
        vc.tableView.height = 50 * vc.dataSource.count * 2 + 200;
        [vc.tableView reloadData];
    };
    
    _lifeNC = [[UINavigationController alloc] initWithRootViewController:lifeVC];
    _deadNC = [[UINavigationController alloc] initWithRootViewController:deadVC];
    
    [self addChildViewController:self.deadNC];
    [self addChildViewController:self.lifeNC];
    self.mainVC = lifeVC;
    
    UIBarButtonItem *menuItemL = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menuB"] style:UIBarButtonItemStylePlain target:self action:@selector(menuWithBlock:)];
    lifeVC.navigationItem.leftBarButtonItem = menuItemL;
    UIBarButtonItem *menuItemD = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menuW"] style:UIBarButtonItemStylePlain target:self action:@selector(menuWithBlock:)];
    deadVC.navigationItem.leftBarButtonItem = menuItemD;
    
//    [self.view addSubview:self.deadNC.view];
    [self.view addSubview:self.lifeNC.view];
    
    self.view.backgroundColor = [UIColor grayColor];
    self.tableView.backgroundColor = [UIColor grayColor];
    
    [self createMulUsers];
}

- (void)createMulUsers {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.tableView.width, 100)];
    view.backgroundColor = [[UIColor blueColor] colorWithAlphaComponent:0.3];
    UITapGestureRecognizer *changeUser = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeUser)];
    [view addGestureRecognizer:changeUser];
    self.tableView.tableHeaderView = view;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 35, 100, 30)];
    label.textAlignment = NSTextAlignmentRight;
    label.text = @"当前用户：";
    label.textColor = [UIColor whiteColor];
    [view addSubview:label];
    
    _usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 35, 100, 30)];
    _usernameLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"];
    [view addSubview:_usernameLabel];
}

- (void)changeUser {
    UserTableViewController *userTVC = [[UserTableViewController alloc] initWithStyle:UITableViewStylePlain];
    userTVC.changeBlock = ^{
        self.usernameLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"];
    };
    UINavigationController *userNC = [[UINavigationController alloc] initWithRootViewController:userTVC];
    [self presentViewController:userNC animated:YES completion:nil];
    [self menuWithBlock:nil];
}

- (void)tap:(UITapGestureRecognizer *)sender {
    [self menuWithBlock:nil];
}

- (void)menuWithBlock:(id)block {
    if (self.isOpen) {
        [self.mainVC.view removeGestureRecognizer:self.tap];
        [UIView animateWithDuration:0.3 animations:^{
            self.tableView.transform = CGAffineTransformMakeScale(2, 2);
            self.mainVC.navigationController.view.transform = CGAffineTransformMakeScale(1, 1);
            CGRect frame = self.mainVC.navigationController.view.frame;
            frame.origin.x = 0;
            self.mainVC.navigationController.view.frame = frame;
            self.isOpen = NO;
        } completion:^(BOOL finished) {
            if (block && ![block isMemberOfClass:[UIBarButtonItem class]]) {
                ((void(^)())block)();
            }
        }];
    } else {
        [self.mainVC.view addGestureRecognizer:self.tap];
        [UIView animateWithDuration:0.3 animations:^{
            self.tableView.transform = CGAffineTransformMakeScale(1, 1);
            self.mainVC.navigationController.view.transform = CGAffineTransformMakeScale(0.8, 0.8);
            CGRect frame = self.mainVC.navigationController.view.frame;
            frame.origin.x = kScreenWidth * 0.85;
            self.mainVC.navigationController.view.frame = frame;
            self.isOpen = YES;
        } completion:^(BOOL finished) {
            if (block && ![block isMemberOfClass:[UIBarButtonItem class]]) {
                ((void(^)())block)();
            }
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor grayColor];
    if (self.dataSource.count == 4 && indexPath.row == 1) {
        if (![[NSUserDefaults standardUserDefaults] boolForKey:@"deadTimeEnable"]) {
            [self.dataSource replaceObjectAtIndex:1 withObject:@"关闭死之钟"];
        } else {
            [self.dataSource replaceObjectAtIndex:1 withObject:@"打开死之钟"];
        }
    }
    cell.textLabel.text = [self.dataSource objectAtIndex:indexPath.row];
    cell.textLabel.textColor = [UIColor whiteColor];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    switch (indexPath.row) {
        case 0:
            if (self.dataSource.count == 4) {
                [self menuWithBlock:^{
                    [self.lifeNC.viewControllers.firstObject startLifeWithAnimation:YES];
                }];
            } else {
                [self menuWithBlock:^{
                    [self.deadNC.viewControllers.firstObject startAnimation:YES];
                }];
            }
            break;
        case 1:
            if (self.dataSource.count == 4) {
                if ([self.lifeNC.viewControllers.firstObject deadTimeButton].enabled) {
                    [self.lifeNC.viewControllers.firstObject deadTimeButton].enabled = NO;
                    [[self.lifeNC.viewControllers.firstObject deadTimeButton] setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                    [SVProgressHUD showSuccessWithStatus:@"死之钟已关闭"];
                    
                } else {
                    [self.lifeNC.viewControllers.firstObject deadTimeButton].enabled = YES;
                    [[self.lifeNC.viewControllers.firstObject deadTimeButton] setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    [SVProgressHUD showSuccessWithStatus:@"死之钟已打开"];
                }
                [self menuWithBlock:^{
//                    [SVProgressHUD dismissWithDelay:1.5];
                    [[NSUserDefaults standardUserDefaults] setBool:![[NSUserDefaults standardUserDefaults] boolForKey:@"deadTimeEnable"] forKey:@"deadTimeEnable"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }];
            } else {
                if ([MFMailComposeViewController canSendMail]) {
                    MFMailComposeViewController *myMailComposeViewController = [[MFMailComposeViewController alloc] init];
                    
                    [myMailComposeViewController setSubject:@"意见反馈"];
                    [myMailComposeViewController setToRecipients:@[@"xiangsideyi@outlook.com"]];
//                    [myMailComposeViewController setCcRecipients:@[@"lanou3g@126.com"]];
//                    [myMailComposeViewController setMessageBody:@"lanou3g" isHTML:YES];
                    
                    myMailComposeViewController.mailComposeDelegate = self;
                    
                    [self presentViewController:myMailComposeViewController animated:YES completion:nil];
                } else {
                    NSLog(@"mail open fail...");
                }
            }
            break;
//        case 2:
//            if (self.dataSource.count == 5) {
//                WishViewController *wishVC = [[WishViewController alloc] init];
//                [self.lifeNC pushViewController:wishVC animated:YES];
//            } else {
//            }
//            [self menuWithBlock:nil];
            break;
        case 2:
            if (self.dataSource.count == 4) {
                if ([MFMailComposeViewController canSendMail]) {
                    MFMailComposeViewController *myMailComposeViewController = [[MFMailComposeViewController alloc] init];
                    
                    [myMailComposeViewController setSubject:@"意见反馈"];
                    [myMailComposeViewController setToRecipients:@[@"xiangsideyi@outlook.com"]];
//                    [myMailComposeViewController setCcRecipients:@[@"lanou3g@126.com"]];
//                    [myMailComposeViewController setMessageBody:@"" isHTML:YES];
                    
                    myMailComposeViewController.mailComposeDelegate = self;
                    
                    [self presentViewController:myMailComposeViewController animated:YES completion:nil];
                } else {
                    NSLog(@"mail open fail...");
                }
            } else {
                NSString *str = nil;
                if ([UIDevice currentDevice].systemVersion.integerValue >= 7.0) {
                    str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@", APPID];
                } else {
                    str = [NSString stringWithFormat:@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@", APPID];
                }
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
            }
            [self menuWithBlock:nil];
            break;
        case 3:
            if (self.dataSource.count == 4) {
                NSString *str = nil;
                if ([UIDevice currentDevice].systemVersion.integerValue >= 7.0) {
                    str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@",APPID];
                } else {
                    str = [NSString stringWithFormat:@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@", APPID];
                }
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
            }
            
            [self menuWithBlock:nil];
            break;
            
        default:
            break;
    }
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    
    switch (result) {
        case MFMailComposeResultCancelled:
            break;
        case MFMailComposeResultFailed:
            [SVProgressHUD showErrorWithStatus:@"邮件发送失败"];
            break;
        case MFMailComposeResultSent:
            [SVProgressHUD showSuccessWithStatus:@"邮件发送成功"];
            break;
        case MFMailComposeResultSaved:
            [SVProgressHUD setMinimumDismissTimeInterval:2];
            [SVProgressHUD showSuccessWithStatus:@"邮件已被保存在邮箱中"];
            [SVProgressHUD setMinimumDismissTimeInterval:0];
            break;
            
        default:
            break;
    }
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
